<template>
    <div class="bg">
        <div class="login">
            <div class="logo">
                <img :src="logo" alt="" width="70px" height="70px">
                <h1 class="ml">wadi后台管理平台</h1>
            </div>
            <el-form :model="ruleForm" :rules="rules" ref="formRef" @submit.prevent="handleLogin">
                <el-form-item prop="username">
                    <el-input v-model="ruleForm.username" placeholder="请输入用户名" prefix-icon="User" />
                </el-form-item>
                <el-form-item prop="password">
                    <el-input v-model="ruleForm.password" placeholder="请输入密码" prefix-icon="Lock" type="password" @keyup.enter="handleLogin"/>
                </el-form-item>
                <el-form-item>
                    <el-checkbox v-model="ruleForm.rememberPassword">记住密码</el-checkbox>
                </el-form-item>
                <el-form-item style="margin-bottom: 0;">
                    <el-button type="primary" style="width: 100%; height: 48px; font-size: 18px; font-weight: 500;" @click="handleLogin">登录</el-button>
                </el-form-item>
            </el-form>
        </div>
    </div>
</template>
<script setup lang="ts">
import logo from "@/assets/logo.png"
import { reactive,ref, onMounted } from "vue";
import type { FormRules,FormInstance } from 'element-plus'
import { ElLoading } from 'element-plus'
import {useUserStore} from "@/store/auth.ts"
import { useRouter } from "vue-router";
interface RuleForm {
    username: string;
    password: string;
    rememberPassword: boolean;
}
const ruleForm: RuleForm = reactive({
    username: "",
    password: "",
    rememberPassword: false
})
const rules = reactive<FormRules<RuleForm>>({
    username: [
        { required: true, message: "用户名不能为空", trigger: "blur" },
        { min: 2, message: "用户名至少需要2个字符", trigger: "blur" }
    ],
    password: [
        { required: true, message: "密码不能为空", trigger: "blur" }, 
    ]
})
const formRef=ref<FormInstance>();
const userStore=useUserStore()
const router=useRouter()

// 保存账号密码到localStorage
const saveCredentials = (username: string, password: string) => {
    localStorage.setItem('rememberedUsername', username)
    localStorage.setItem('rememberedPassword', password)
}

// 从localStorage获取账号密码
const loadCredentials = () => {
    const savedUsername = localStorage.getItem('rememberedUsername')
    const savedPassword = localStorage.getItem('rememberedPassword')
    
    if (savedUsername && savedPassword) {
        ruleForm.username = savedUsername
        ruleForm.password = savedPassword
        ruleForm.rememberPassword = true
    }
}

// 清除保存的账号密码
const clearCredentials = () => {
    localStorage.removeItem('rememberedUsername')
    localStorage.removeItem('rememberedPassword')
}

// 组件挂载时检查是否有保存的账号密码
onMounted(() => {
    loadCredentials()
})
const handleLogin=()=>{
    formRef.value?.validate(async (valid:boolean)=>{ //?. 可选链操作符   obj?obj.name:"" obj?.name
        if(valid){
            //校验通过
            const loading = ElLoading.service({
                lock: true,
                text: '登录中...',
                background: 'rgba(0, 0, 0, 0.7)'
            })
            
            try {
                await userStore.login(ruleForm);
                
                // 登录成功后才保存账号密码
                if (ruleForm.rememberPassword) {
                    saveCredentials(ruleForm.username, ruleForm.password)
                } else {
                    // 如果取消勾选记住密码，清除保存的账号密码
                    clearCredentials()
                }
                
                router.push("/")
            } catch (error) {
                console.error('登录失败:', error);
                // 登录失败不保存账号密码
                // 错误已经在响应拦截器中显示了通知
            } finally {
                loading.close()
            }
        }
    })
}
</script>

<style lang="less" scoped>
.bg {
    background-image: url("../assets/bg.png");
    background-size: cover;
    background-position: center;
    background-repeat: no-repeat;
    height: 100vh;

    .login {
        width: 500px;
        min-height: 400px;
        padding: 50px;
        background: white;
        border-radius: 8px;
        box-shadow: 0 0 20px rgba(0, 0, 0, 0.1);
        text-align: center;
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);

        .logo {
            display: flex;
            justify-content: center;
            align-items: center;
            margin-bottom: 40px;

            h1 {
                color: rgb(14, 53, 148);
            }
        }
        // 新增：让输入框和按钮更大气
        ::v-deep .el-input__inner {
            height: 48px;
            font-size: 16px;
            border-radius: 6px;
        }
        ::v-deep .el-form-item {
            margin-bottom: 24px;
        }
        ::v-deep .el-button--primary {
            height: 48px;
            font-size: 18px;
            font-weight: 500;
            border-radius: 6px;
        }
        ::v-deep .el-checkbox {
            font-size: 14px;
        }
    }
}
</style>